package com.example.examsystem.controller;

import com.example.examsystem.model.User;
import com.example.examsystem.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/debug")
@RequiredArgsConstructor
public class DebugController {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final RedisTemplate<String, Object> redisTemplate;
    
    @GetMapping("/status")
    public ResponseEntity<?> getStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("timestamp", System.currentTimeMillis());
        status.put("message", "Debug API is working");
        
        try {
            long userCount = userRepository.count();
            status.put("userCount", userCount);
            
            User admin = userRepository.findByUsername("admin").orElse(null);
            if (admin != null) {
                status.put("adminExists", true);
                status.put("adminEnabled", admin.getEnabled());
                status.put("adminLocked", admin.getAccountLocked());
            } else {
                status.put("adminExists", false);
            }
            
        } catch (Exception e) {
            status.put("databaseError", e.getMessage());
        }
        
        return ResponseEntity.ok(status);
    }
    
    @PostMapping("/test-password")
    public ResponseEntity<?> testPassword(@RequestBody Map<String, String> request) {
        String rawPassword = request.get("password");
        String username = request.get("username");
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            User user = userRepository.findByUsername(username).orElse(null);
            if (user == null) {
                result.put("error", "User not found");
                return ResponseEntity.ok(result);
            }
            
            boolean matches = passwordEncoder.matches(rawPassword, user.getPassword());
            result.put("passwordMatches", matches);
            result.put("userEnabled", user.getEnabled());
            result.put("userLocked", user.getAccountLocked());
            
        } catch (Exception e) {
            result.put("error", e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
    
    @GetMapping("/mappings")
    public ResponseEntity<?> getMappings() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "Available endpoints");
        response.put("endpoints", Arrays.asList(
            "/api/debug/status",
            "/api/debug/mappings", 
            "/api/auth/login",
            "/api/captcha/image",
            "/api/captcha/sms"
        ));
        return ResponseEntity.ok(response);
    }

    @GetMapping("/redis")
    public ResponseEntity<?> testRedis() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 测试Redis连接
            redisTemplate.opsForValue().set("test:connection", "success", 10, TimeUnit.SECONDS);
            String result = (String) redisTemplate.opsForValue().get("test:connection");
            
            response.put("success", true);
            response.put("redis_status", "connected");
            response.put("test_result", result);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("redis_status", "failed");
            response.put("error", e.getMessage());
            
            return ResponseEntity.status(500).body(response);
        }
    }

    @PostMapping("/check-login")
    public ResponseEntity<?> checkLogin(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String password = request.get("password");
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查用户是否存在
            User user = userRepository.findByUsername(username).orElse(null);
            if (user == null) {
                result.put("userExists", false);
                return ResponseEntity.ok(result);
            }
            
            result.put("userExists", true);
            result.put("username", user.getUsername());
            result.put("enabled", user.getEnabled());
            result.put("accountLocked", user.getAccountLocked());
            result.put("storedPasswordPrefix", user.getPassword().substring(0, 20) + "...");
            
            // 检查密码是否匹配
            boolean passwordMatches = passwordEncoder.matches(password, user.getPassword());
            result.put("passwordMatches", passwordMatches);
            
            // 测试加密新密码
            String encodedPassword = passwordEncoder.encode(password);
            result.put("newEncodedPassword", encodedPassword.substring(0, 20) + "...");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("error", e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    @PostMapping("/reset-admin-password")
    public ResponseEntity<?> resetAdminPassword() {
        try {
            User admin = userRepository.findByUsername("admin").orElse(null);
            if (admin == null) {
                return ResponseEntity.ok(Map.of("success", false, "message", "Admin user not found"));
            }
            
            // 重新设置密码为123456
            String newPassword = passwordEncoder.encode("123456");
            admin.setPassword(newPassword);
            userRepository.save(admin);
            
            return ResponseEntity.ok(Map.of(
                "success", true, 
                "message", "Admin password reset to 123456",
                "newPasswordPrefix", newPassword.substring(0, 20) + "..."
            ));
            
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of("success", false, "error", e.getMessage()));
        }
    }
}

